/* Includes--------------------------------------------- */
#include "wav.h"
#include "string.h"

/* Define----------------------------------------------- */
/* Private funtion delaration--------------------------- */
/* Private variables------------------------------------ */
static WAV_FILE_HEADER WavFileHeader;
static LIST list;
static DATA data;
static DWORD current_pos = 0, total_size;

/* External variables----------------------------------- */
/* External functions----------------------------------- */
DWORD WavGetFileHeader(BYTE *buff, DWORD size) {
  DWORD pos;

  if (size > sizeof(WavFileHeader)) {
    pos = sizeof(WavFileHeader);
    memcpy(&WavFileHeader, buff, pos);
    memcpy(&list, buff + pos, 8);
    pos = pos + 8 + list.listSize;
    memcpy(&data, buff + pos, 8);
    pos += 8;
    return pos;
  }
  return 0;
}

WORD WavGetChannelNum(void) {
  return WavFileHeader.pcmWaveFormat.wf.nChannls;
}

DWORD WavGetSampleRate(void) {
  return WavFileHeader.pcmWaveFormat.wf.nSamplesPerSec;
}

DWORD WavGetBitRate(void) {
  return WavFileHeader.pcmWaveFormat.wf.nAvgBytesperSec;
}

DWORD WavGetSound(BYTE *buff, DWORD size, WORD *data) {
  DWORD length = 0;
  WORD temp[2] = {0};

  if (WavGetChannelNum() == 1) {
    while (length < size) {
      temp[0] = *(buff + length++);
      temp[1] = *(buff + length++);
      *data++ = (temp[1] << 8) | temp[0];
    }
  }
  return length / 2;
}

DWORD WavGetLeftSound(BYTE *buff, DWORD size, WORD *data) {
  DWORD length = 0;
  WORD temp[2] = {0};

  if (WavGetChannelNum() > 1) {
    while (length < size) {
      temp[0] = *(buff + length++);
      temp[1] = *(buff + length++);
      *data++ = (temp[1] << 8) | temp[0];
      length += 2;
    }
  }
  return length / 4;
}

DWORD WavGetRightSound(BYTE *buff, DWORD size, WORD *data) {
  DWORD length = 0;
  WORD temp[2] = {0};

  if (WavGetChannelNum() > 1) {
    while (length < size) {
      length += 2;
      temp[0] = *(buff + length++);
      temp[1] = *(buff + length++);
      *data++ = (temp[1] << 8) | temp[0];
    }
  }
  return length / 4;
}

/* Private functions------------------------------------ */
/* End of file------------------------------------------ */
